package com.lc.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.lc.admin.base.PageResponse;
import com.lc.admin.dto.PendingTaskDto;
import com.lc.admin.service.PendingTaskService;
import com.lc.admin.utils.StringUtils;
import com.lc.admin.utils.UserThreadLocal;
import com.lc.admin.vo.PendingTaskVO;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 查询我的待办任务
 */
@Service
public class PendingTaskServiceImpl implements PendingTaskService {

    @Autowired
    HistoryService historyService;


    @Override
    public PageResponse<List<PendingTaskVO>> selectByPage(PendingTaskDto pendingTaskDto) {
        // 判断用户角色，养老顾问就查询formKey=0的，护理主管就查询formKey=1的
        // 新增一个用户id为assignee

        // activiti中查询任务或历史即可。默认查询待处理的任务
        // 当前需要执行的步骤在历史表中也有记录，所以可以直接查询历史任务表即可。
        // 取出上一步设置的全局变量：query.processVariablesValueEquals("key",用户传递的值)
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
        // 过滤我自己的数据，取出当前登录用户的信息
        historicTaskInstanceQuery.taskAssignee(UserThreadLocal.getMgtUserId()+"");
        // 单据编号条件
        if(!StringUtils.isEmpty(pendingTaskDto.getCode())) {
            // 模糊查询
            historicTaskInstanceQuery.processVariableValueEquals("code", pendingTaskDto.getCode());
        }
        // 单据类别
        if(ObjectUtil.isNotEmpty(pendingTaskDto.getType())) {
            historicTaskInstanceQuery.processVariableValueEquals("type",pendingTaskDto.getType());
        }
        // 流程状态
        if(ObjectUtil.isNotEmpty(pendingTaskDto.getStatus())) {
            historicTaskInstanceQuery.processVariableValueEquals("status",pendingTaskDto.getStatus());
        }
        // 申请人
        if(!StringUtils.isEmpty(pendingTaskDto.getApplicat())) {
            historicTaskInstanceQuery.taskAssignee(pendingTaskDto.getAssigneeId()+"");
        }
        // 申请时间
        if(ObjectUtil.isNotEmpty(pendingTaskDto.getStartTime()) && ObjectUtil.isNotEmpty(pendingTaskDto.getEndTime())) {
            historicTaskInstanceQuery.taskCreatedAfter(pendingTaskDto.getStartTime()).taskCreatedBefore(pendingTaskDto.getEndTime());
        } else if(ObjectUtil.isNotEmpty(pendingTaskDto.getStartTime()) && ObjectUtil.isEmpty(pendingTaskDto.getEndTime())) {
            historicTaskInstanceQuery.taskCreatedAfter(pendingTaskDto.getStartTime());
        } else if(ObjectUtil.isEmpty(pendingTaskDto.getStartTime()) && ObjectUtil.isNotEmpty(pendingTaskDto.getEndTime())) {  // 只有结束时间
            historicTaskInstanceQuery.taskCreatedBefore(pendingTaskDto.getEndTime());
        }

        // 已处理，待处理
        if(ObjectUtil.isNotEmpty(pendingTaskDto.getIsHandle())) {
            if(pendingTaskDto.getIsHandle() == 1) {
                historicTaskInstanceQuery.finished();
            } else {
                historicTaskInstanceQuery.unfinished();
            }
        }

        List<PendingTaskVO> taskVo = new ArrayList<>();
        // limit 0 5
        // limit 5,5
        // limit 10,5
        // limit (pageNum-1)*pageSize  pageSize

        long count = historicTaskInstanceQuery.includeProcessVariables().count();

        List<HistoricTaskInstance> list = historicTaskInstanceQuery.includeProcessVariables().listPage((pendingTaskDto.getPageNum()-1)* pendingTaskDto.getPageSize(),pendingTaskDto.getPageSize());
        for (HistoricTaskInstance historicTaskInstance : list) {
            // 该方法获取的是 流程实例的变量（process variables），而不是任务变量。
            // 如果流程实例已经结束，这些变量可能已经被清除，返回空 Map
            Map<String, Object> variables = historicTaskInstance.getProcessVariables();
            // 转换为  PendingTaskVO
            PendingTaskVO pendingTaskVO = new PendingTaskVO();
            pendingTaskVO.setId(historicTaskInstance.getId());
            pendingTaskVO.setAssignee(historicTaskInstance.getProcessVariables().get("user0Name").toString());
            pendingTaskVO.setCheckInId(historicTaskInstance.getProcessVariables().get("checkInId").toString());
            pendingTaskVO.setApplicationTime(historicTaskInstance.getCreateTime());
            pendingTaskVO.setCode(historicTaskInstance.getProcessVariables().get("code").toString());
            pendingTaskVO.setStatus(Integer.parseInt(historicTaskInstance.getProcessVariables().get("status").toString()));
            pendingTaskVO.setAssigneeId(historicTaskInstance.getAssignee());
            pendingTaskVO.setTitle(historicTaskInstance.getProcessVariables().get("title").toString());  // ??
            pendingTaskVO.setType(Integer.parseInt(historicTaskInstance.getProcessVariables().get("type").toString()));

            taskVo.add(pendingTaskVO);
        }
        // pages：总共多少页
        // 已知每页条数：10    pendingTaskDto.getPageSize()
        // 已知总条数： count
        long pages = count % pendingTaskDto.getPageSize() == 0 ? count / pendingTaskDto.getPageSize() : count / pendingTaskDto.getPageSize() + 1;

        // count：总共多少条
        PageResponse pageResponse = PageResponse.of(taskVo, pendingTaskDto.getPageNum(), pendingTaskDto.getPageSize(), pages, count);

        return pageResponse;
    }
}
